<script setup>
// ========================
// 物品管理页面逻辑（带详细注释）
// ========================

// 引入子组件（用户选择弹窗）
import SelectUser from '../user/SelectUser.vue'
// 引入 Vue3 Composition API 相关方法
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from 'vue'

// 获取全局属性（如 $axios, $httpUrl, $message）
// proxy.$axios 用于发起请求，proxy.$message 用于全局消息提示
const { proxy } = getCurrentInstance()

// 当前登录用户信息（从 sessionStorage 获取）
const user = ref(JSON.parse(sessionStorage.getItem('CurUser')))

// ========== 页面数据相关 =============
// 仓库下拉数据
const storageData = ref([])
// 分类下拉数据
const goodstypeData = ref([])
// 物品表格数据
const tableData = ref([])
// 分页相关
const pageSize = ref(10) // 每页条数
const pageNum = ref(1)   // 当前页码
const total = ref(0)     // 总条数
// 查询条件
const name = ref('')     // 物品名
const storage = ref('')  // 仓库
const goodstype = ref('')// 分类
// 弹窗控制
const centerDialogVisible = ref(false) // 物品维护弹窗
const inDialogVisible = ref(false)     // 出入库弹窗
const innerVisible = ref(false)        // 用户选择弹窗
// 当前选中行、临时用户
const currentRow = ref({})
const tempUser = ref({})

// ========== 表单数据 =============
// 物品维护表单数据
const form = reactive({
    id: '',
    name: '',
    storage: '',
    goodstype: '',
    count: '',
    remark: ''
})
// 出入库表单数据
const form1 = reactive({
    goods: '',
    goodsname: '',
    count: '',
    username: '',
    userid: '',
    adminId: '',
    remark: '',
    action: '1' // 1-入库 2-出库
})

// ========== 表单校验规则 =============
// 物品维护表单校验
const rules = {
    name: [
        { required: true, message: '请输入物品名', trigger: 'blur' }
    ],
    storage: [
        { required: true, message: '请选择仓库', trigger: 'blur' }
    ],
    goodstype: [
        { required: true, message: '请选择分类', trigger: 'blur' }
    ],
    count: [
        { required: true, message: '请输入数量', trigger: 'blur' },
        { pattern: /^([1-9][0-9]*){1,4}$/, message: '数量必须为正整数字', trigger: 'blur' },
        {
            // 自定义校验：数量不能大于9999
            validator: (rule, value, callback) => {
                if (value > 9999) {
                    callback(new Error('数量输入过大'))
                } else {
                    callback()
                }
            }, trigger: 'blur'
        }
    ]
}
// 出入库表单校验（目前无规则）
const rules1 = {}

// ========== ref 绑定表单实例 =============
const formRef = ref()   // 物品维护表单ref
const form1Ref = ref()  // 出入库表单ref

// ========== 事件与方法 =============

// 用户选择弹窗回调，选中用户后赋值到临时变量
function doSelectUser(val) {
    tempUser.value = val
}
// 确认选择用户，将用户信息写入出入库表单
function confirmUser() {
    form1.username = tempUser.value.name
    form1.userid = tempUser.value.id
    innerVisible.value = false
}

// 表格当前行变化，记录选中行
function selectCurrentChange(val) {
    currentRow.value = val
}

// 格式化表格显示：根据id查找仓库/分类名称
function formatStorage(row) {
    const temp = storageData.value.find(item => item.id == row.storage)
    return temp && temp.name
}
function formatGoodstype(row) {
    const temp = goodstypeData.value.find(item => item.id == row.goodstype)
    return temp && temp.name
}

// 重置物品维护表单
function resetForm() {
    formRef.value && formRef.value.resetFields()
}
// 重置出入库表单
function resetInForm() {
    form1Ref.value && form1Ref.value.resetFields()
}

// 删除物品，调用后端接口，成功后刷新列表
function del(id) {
    proxy.$axios.get(proxy.$httpUrl + '/goods/del?id=' + id).then(res => res.data).then(res => {
        if (res.code == 200) {
            proxy.$message({ message: '操作成功！', type: 'success' })
            loadPost()
        } else {
            proxy.$message({ message: '操作失败！', type: 'error' })
        }
    })
}

// 编辑物品，弹出维护弹窗并填充表单
function mod(row) {
    centerDialogVisible.value = true
    nextTick(() => {
        form.id = row.id
        form.name = row.name
        form.storage = row.storage
        form.goodstype = row.goodstype
        form.count = row.count
        form.remark = row.remark
    })
}

// 新增物品，弹出维护弹窗并重置表单
function add() {
    centerDialogVisible.value = true
    nextTick(() => {
        resetForm()
        form.id = ''
    })
}

// 入库操作，弹出出入库弹窗并初始化表单
function inGoods() {
    if (!currentRow.value.id) {
        alert('请选择记录')
        return
    }
    inDialogVisible.value = true
    nextTick(() => {
        resetInForm()
    })
    form1.goodsname = currentRow.value.name
    form1.goods = currentRow.value.id
    form1.adminId = user.value.id
    form1.action = '1' // 入库
}

// 出库操作，弹出出入库弹窗并初始化表单
function outGoods() {
    if (!currentRow.value.id) {
        alert('请选择记录')
        return
    }
    inDialogVisible.value = true
    nextTick(() => {
        resetInForm()
    })
    form1.goodsname = currentRow.value.name
    form1.goods = currentRow.value.id
    form1.adminId = user.value.id
    form1.action = '2' // 出库
}

// 打开用户选择弹窗
function selectUser() {
    innerVisible.value = true
}

// 保存物品，新增时调用
function doSave() {
    proxy.$axios.post(proxy.$httpUrl + '/goods/save', form).then(res => res.data).then(res => {
        if (res.code == 200) {
            proxy.$message({ message: '操作成功！', type: 'success' })
            centerDialogVisible.value = false
            loadPost()
            resetForm()
        } else {
            proxy.$message({ message: '操作失败！', type: 'error' })
        }
    })
}

// 修改物品，编辑时调用
function doMod() {
    proxy.$axios.post(proxy.$httpUrl + '/goods/update', form).then(res => res.data).then(res => {
        if (res.code == 200) {
            proxy.$message({ message: '操作成功！', type: 'success' })
            centerDialogVisible.value = false
            loadPost()
            resetForm()
        } else {
            proxy.$message({ message: '操作失败！', type: 'error' })
        }
    })
}

// 表单提交，区分新增/编辑
function save() {
    formRef.value.validate(valid => {
        if (valid) {
            if (form.id) {
                doMod()
            } else {
                doSave()
            }
        } else {
            return false
        }
    })
}

// 出入库操作，调用后端接口
function doInGoods() {
    proxy.$axios.post(proxy.$httpUrl + '/record/save', form1).then(res => res.data).then(res => {
        if (res.code == 200) {
            proxy.$message({ message: '操作成功！', type: 'success' })
            inDialogVisible.value = false
            loadPost()
            resetInForm()
        } else {
            proxy.$message({ message: '操作失败！', type: 'error' })
        }
    })
}

// 分页：每页条数变化
function handleSizeChange(val) {
    pageNum.value = 1
    pageSize.value = val
    loadPost()
}
// 分页：页码变化
function handleCurrentChange(val) {
    pageNum.value = val
    loadPost()
}

// 重置查询参数
function resetParam() {
    name.value = ''
    storage.value = ''
    goodstype.value = ''
}

// 查询物品列表，带分页和条件
function loadPost() {
    proxy.$axios.post(proxy.$httpUrl + '/goods/listPage', {
        pageSize: pageSize.value,
        pageNum: pageNum.value,
        param: {
            name: name.value,
            goodstype: goodstype.value + '',
            storage: storage.value + ''
        }
    }).then(res => res.data).then(res => {
        if (res.code == 200) {
            tableData.value = res.data
            total.value = res.total
        } else {
            alert('获取数据失败')
        }
    })
}

// 查询仓库下拉数据
function loadStorage() {
    proxy.$axios.get(proxy.$httpUrl + '/storage/list').then(res => res.data).then(res => {
        if (res.code == 200) {
            storageData.value = res.data
        } else {
            alert('获取数据失败')
        }
    })
}

// 查询分类下拉数据
function loadGoodstype() {
    proxy.$axios.get(proxy.$httpUrl + '/goodstype/list').then(res => res.data).then(res => {
        if (res.code == 200) {
            goodstypeData.value = res.data
        } else {
            alert('获取数据失败')
        }
    })
}

// 生命周期钩子：页面加载时初始化仓库、分类、物品列表
onMounted(() => {
    loadStorage()
    loadGoodstype()
    loadPost()
})
</script>


<template>
    <div>
        <div style="margin-bottom: 5px;">
            <el-input v-model="name" placeholder="请输入物品名" suffix-icon="el-icon-search" style="width: 200px;"
                @keyup.enter.native="loadPost"></el-input>
            <el-select v-model="storage" placeholder="请选择仓库" style="margin-left: 5px;">
                <el-option v-for="item in storageData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
            </el-select>
            <el-select v-model="goodstype" placeholder="请选择分类" style="margin-left: 5px;">
                <el-option v-for="item in goodstypeData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
            </el-select>

            <el-button type="primary" style="margin-left: 5px;" @click="loadPost">查询</el-button>
            <el-button type="success" @click="resetParam">重置</el-button>

            <el-button type="primary" style="margin-left: 5px;" @click="add" v-if="user.roleId != 2">新增</el-button>
            <el-button type="primary" style="margin-left: 5px;" @click="inGoods" v-if="user.roleId != 2">入库</el-button>
            <el-button type="primary" style="margin-left: 5px;" @click="outGoods" v-if="user.roleId != 2">出库</el-button>
        </div>
        <el-table :data="tableData" :header-cell-style="{ background: '#f2f5fc', color: '#555555' }" border
            highlight-current-row @current-change="selectCurrentChange">
            <el-table-column prop="id" label="ID" width="60">
            </el-table-column>
            <el-table-column prop="name" label="物品名" width="180">
            </el-table-column>
            <el-table-column prop="storage" label="仓库" width="180" :formatter="formatStorage">
            </el-table-column>
            <el-table-column prop="goodstype" label="分类" width="180" :formatter="formatGoodstype">
            </el-table-column>
            <el-table-column prop="count" label="数量" width="180">
            </el-table-column>
            <el-table-column prop="remark" label="备注">
            </el-table-column>
            <el-table-column prop="operate" label="操作" v-if="user.roleId != 2">
                <template slot-scope="scope">
                    <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
                    <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.id)" style="margin-left: 5px;">
                        <el-button slot="reference" size="small" type="danger">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
            :page-sizes="[5, 10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>

        <el-dialog title="物品维护" :visible.sync="centerDialogVisible" width="30%" center>

            <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                <el-form-item label="物品名" prop="name">
                    <el-col :span="20">
                        <el-input v-model="form.name"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="仓库" prop="storage">
                    <el-col :span="20">
                        <el-select v-model="form.storage" placeholder="请选择仓库" style="margin-left: 5px;">
                            <el-option v-for="item in storageData" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>

                    </el-col>
                </el-form-item>
                <el-form-item label="分类" prop="goodstype">
                    <el-col :span="20">
                        <el-select v-model="form.goodstype" placeholder="请选择分类" style="margin-left: 5px;">
                            <el-option v-for="item in goodstypeData" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="数量" prop="count">
                    <el-col :span="20">
                        <el-input v-model="form.count"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-col :span="20">
                        <el-input type="textarea" v-model="form.remark"></el-input>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="出入库" :visible.sync="inDialogVisible" width="30%" center>

            <el-dialog width="75%" title="用户选择" :visible.sync="innerVisible" append-to-body>
                <SelectUser @doSelectUser="doSelectUser"></SelectUser>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="innerVisible = false">取 消</el-button>
                    <el-button type="primary" @click="confirmUser">确 定</el-button>
                </span>
            </el-dialog>

            <el-form ref="form1" :rules="rules1" :model="form1" label-width="80px">
                <el-form-item label="物品名">
                    <el-col :span="20">
                        <el-input v-model="form1.goodsname" readonly></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="申请人">
                    <el-col :span="20">
                        <el-input v-model="form1.username" readonly @click.native="selectUser"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="数量" prop="count">
                    <el-col :span="20">
                        <el-input v-model="form1.count"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-col :span="20">
                        <el-input type="textarea" v-model="form1.remark"></el-input>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="inDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="doInGoods">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>





<style scoped></style>